//
//  SEGCardSwitch.m
//  SEGCardSwitchDemo
//
//  Created by Apple on 2017/1/20.
//  Copyright © 2017年 Apple. All rights reserved.
//

#import "SEGCardSwitch.h"
#import "SEGCardSwitchFlowLayout.h"
#import "SEGCardCell.h"
#import "SEGCardTencentCell.h"
#import "SEGCardPageControl.h"

@interface SEGCardSwitch ()<UICollectionViewDelegate,UICollectionViewDataSource,GDTUnifiedNativeAdViewDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, assign) CGFloat dragStartX;

@property (nonatomic, assign) CGFloat dragEndX;

@property (nonatomic, assign) CGFloat dragAtIndex;

/// 自动轮播定时器
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) SEGCardPageControl* pageControl;
@end

@implementation SEGCardSwitch

- (instancetype)init {
    if (self = [super init]) {
        [self buildUI];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self buildUI];
    }
    return self;
}

-(void)dealloc {
    [self destroyTimer];
}

- (void)buildUI {
    [self addCollectionView];
}

- (void)addCollectionView {
    //避免UINavigation对UIScrollView产生的偏移问题
    [self addSubview:[UIView new]];
    SEGCardSwitchFlowLayout *flowLayout = [[SEGCardSwitchFlowLayout alloc] init];
    __weak typeof(self)weakSelf = self;
    flowLayout.centerBlock = ^(NSIndexPath *indexPath) {
        [weakSelf updateSelectedIndex:indexPath];
    };
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:flowLayout];
    self.collectionView.showsHorizontalScrollIndicator = false;
    self.collectionView.backgroundColor = kColor_W;
    [self.collectionView registerClass:[SEGCardCell class] forCellWithReuseIdentifier:@"SEGCardCell"];
    [self.collectionView registerClass:[SEGCardTencentCell class] forCellWithReuseIdentifier:[SEGCardTencentCell reuseIdentifier]];
    self.collectionView.userInteractionEnabled = true;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self addSubview:self.collectionView];
    
    [self addSubview:self.pageControl];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    self.collectionView.frame = self.bounds;
    self.pageControl.frame = CGRectMake(0, CGRectGetHeight(self.frame)-36, CGRectGetWidth(self.frame), 6);
}

- (void)updateSelectedIndex:(NSIndexPath *)indexPath {
    if (indexPath.row != _selectedIndex) {
        _selectedIndex = indexPath.row;
        [self performScrollDelegateMethod];
    }
}

#pragma mark -
#pragma mark Setter
- (void)setModels:(NSArray<SEGCardDataModel *> *)models {
    _models = models;
    [self.collectionView reloadData];
    [self creatTimer];
    self.pageControl.totalPages = _models.count;
    [self.pageControl setHidden:_models.count <= 1 ? YES : NO];
}

#pragma mark -
#pragma mark CollectionDelegate
//配置cell居中
- (void)fixCellToCenter {
    if (_selectedIndex != [self dragAtIndex]) {
        [self scrollToCenterAnimated:true];
        return;
    }
    //最小滚动距离
    float dragMiniDistance = self.bounds.size.width/20.0f;
    if (self.dragStartX -  self.dragEndX >= dragMiniDistance) {
        _selectedIndex -= 1;//向右
    }else if(self.dragEndX -  self.dragStartX >= dragMiniDistance){
        _selectedIndex += 1;//向左
    }
    NSInteger maxIndex = [self.collectionView numberOfItemsInSection:0] - 1;
    _selectedIndex = _selectedIndex <= 0 ? 0 : _selectedIndex;
    _selectedIndex = _selectedIndex >= maxIndex ? maxIndex : _selectedIndex;
    [self scrollToCenterAnimated:true];
}

//滚动到中间
- (void)scrollToCenterAnimated:(BOOL)animated {
    self.pageControl.currentIndex = _selectedIndex;
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:_selectedIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
}

//手指拖动开始
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self destroyTimer];
    if (!_pagingEnabled) {return;}
    self.dragStartX = scrollView.contentOffset.x;
    self.dragAtIndex = _selectedIndex;
}

//手指拖动停止
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (!_pagingEnabled) {return;}
    self.dragEndX = scrollView.contentOffset.x;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self fixCellToCenter];
    });
}

//点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    _selectedIndex = indexPath.row;
    [self scrollToCenterAnimated:YES];
    [self performClickDelegateMethod];
    // 系统广告跳转
    if ([self.models[indexPath.row].channel isEqualToString:@"SYS"]) {
        SEGAdvertismentModel *model = self.models[indexPath.row].SYSData;
        [[SEGUhomeMediator sharedInstance] seg_pushToViewControllerWithType:[model yy_modelToJSONObject]];
    }
}

#pragma mark -
#pragma mark CollectionDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.models.count;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    // 腾讯广告
    SEGCardDataModel *data = self.models[indexPath.row];
    
    if ([data.channel isEqualToString:@"GDT"]) {
        SEGCardTencentCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:[SEGCardTencentCell reuseIdentifier] forIndexPath:indexPath];
        cell.adView.viewController = self.vc; // 跳转 VC
        cell.adView.delegate = self;
        [cell.adView updateData:data.GDTData];
        [cell.adView registerDataObject:data.GDTData clickableViews:@[cell.adView,cell.adView.imageView]];
        return  cell;
    }
    
    // 系统广告
    static NSString* cellId = @"SEGCardCell";
    SEGCardCell* card = [collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];
    card.model = data.SYSData;
    return  card;
}

#pragma mark -
#pragma mark 功能方法
- (void)setSelectedIndex:(NSInteger)selectedIndex {
    _selectedIndex = selectedIndex;
    [self switchToIndex:selectedIndex animated:false];
}

- (void)switchToIndex:(NSInteger)index animated:(BOOL)animated {
    _selectedIndex = index;
    self.pageControl.currentIndex = index;
    [self scrollToCenterAnimated:animated];
}

- (void)performClickDelegateMethod {
    if ([_delegate respondsToSelector:@selector(cardSwitchDidClickAtIndex:)]) {
        [_delegate cardSwitchDidClickAtIndex:_selectedIndex];
    }
}

- (void)performScrollDelegateMethod {
    if ([_delegate respondsToSelector:@selector(cardSwitchDidScrollToIndex:)]) {
        [_delegate cardSwitchDidScrollToIndex:_selectedIndex];
    }
}

# pragma mark - 时间

-(void)creatTimer {
    if (self.models && self.models.count > 1) {
        [self destroyTimer];
        NSTimer *timer = [NSTimer timerWithTimeInterval:3 target:self selector:@selector(startScrollAutomtically) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
        self.timer = timer;
    }
}

-(void)destroyTimer {
    if(self.timer) [self.timer invalidate];
    self.timer = nil;
}

-(void)startScrollAutomtically {
    NSInteger index = self.selectedIndex + 1;
    index = index > self.models.count - 1 ? self.models.count - 1 : index;
    
     NSLog(@"%zd---%zd---%zd",self.selectedIndex,index,self.models.count);
    
    if (index == self.selectedIndex ) {
        [self switchToIndex:0 animated:true];
    }else{
        [self switchToIndex:index animated:true];
    }
    
    
//    NSInteger currentIndex = self.currentIndex + 1;
//    currentIndex = (currentIndex == self.dataSources.count) ? 1 : currentIndex;
//    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:currentIndex inSection:0];
//    [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
//    self.currentIndex = currentIndex;
}

//手指拖动开始
-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
    [self creatTimer];
}


-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
//    CGFloat width = self.frame.size.width;
//    NSInteger index = (scrollView.contentOffset.x + width * 0.5) / width;
//
//    NSArray *indexPaths = [self.collectionView indexPathsForVisibleItems];
//    NSIndexPath *indexPath = indexPaths.firstObject;
//
//    NSLog(@"%zd--%zd--%zd",index,self.models.count,indexPath.row);
//    //当滚动到最后一张图片时，继续滚向后动跳到第一张
//    if (indexPath.row == self.models.count - 1) {
//        [self switchToIndex:0 animated:NO];
//        return;
//    }
}

#pragma mark - GDTUnifiedNativeAdViewDelegate
- (void)gdt_unifiedNativeAdViewWillExpose:(GDTUnifiedNativeAdView *)unifiedNativeAdView{
  NSLog(@"广告曝光回调,%s",__FUNCTION__);
}
- (void)gdt_unifiedNativeAdViewDidClick:(GDTUnifiedNativeAdView *)unifiedNativeAdView{
  NSLog(@"广告点击回调,%s",__FUNCTION__);
}
- (void)gdt_unifiedNativeAdDetailViewClosed:(GDTUnifiedNativeAdView *)unifiedNativeAdView{
  NSLog(@"广告详情页关闭回调,%s",__FUNCTION__);
}
- (void)gdt_unifiedNativeAdViewApplicationWillEnterBackground:(GDTUnifiedNativeAdView *)unifiedNativeAdView{
  NSLog(@"当点击应用下载或者广告调用系统程序打开时调用,%s",__FUNCTION__);
}
- (void)gdt_unifiedNativeAdDetailViewWillPresentScreen:(GDTUnifiedNativeAdView *)unifiedNativeAdView{
  NSLog(@"广告详情页面即将展示回调,%s",__FUNCTION__);
}
- (void)gdt_unifiedNativeAdView:(GDTUnifiedNativeAdView *)unifiedNativeAdView playerStatusChanged:(GDTMediaPlayerStatus)status userInfo:(NSDictionary *)userInfo{
  NSLog(@"视频广告播放状态更改回调,%s",__FUNCTION__);
}

#pragma mark -Getter
-(SEGCardPageControl *)pageControl {
    if (!_pageControl) {
        _pageControl = [[SEGCardPageControl alloc] init];
    }
    return _pageControl;
}
@end
